package com.ruoyi.lock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.lock.domain.ATenantkey;
import com.ruoyi.lock.mapper.ADeviceMapper;
import com.ruoyi.lock.mapper.ATenantkeyMapper;
import com.ruoyi.lock.service.IATenantkeyService;
import com.ruoyi.locksApi.domain.ATask;
import com.ruoyi.locksApi.mapper.ATaskMapper;
import com.ruoyi.locksApi.service.LockApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 钥匙Service业务层处理
 * 
 * @author arvin
 * @date 2025-03-06
 */
@Service
public class ATenantkeyServiceImpl implements IATenantkeyService 
{
    @Autowired
    private ATenantkeyMapper aTenantkeyMapper;
    @Autowired
    private ADeviceMapper aDeviceMapper;
    @Autowired
    private ATaskMapper taskMapper;
    @Autowired
    private LockApiService lockApiService;

    /**
     * 查询钥匙
     * 
     * @param id 钥匙主键
     * @return 钥匙
     */
    @Override
    public ATenantkey selectATenantkeyById(Long id)
    {
        return aTenantkeyMapper.selectATenantkeyById(id);
    }
    @Override
    public ATenantkey selectATenantkeyById3(Long id)
    {
        return aTenantkeyMapper.selectATenantkeyById3(id);
    }

    /**
     * 查询钥匙列表
     * 
     * @param aTenantkey 钥匙
     * @return 钥匙
     */
    @DataScope(deptAlias = "d")
    @Override
    public List<ATenantkey> selectATenantkeyList(ATenantkey aTenantkey)
    {
        return aTenantkeyMapper.selectATenantkeyList(aTenantkey);
    }
    /**
     * 查询钥匙列表
     *
     * @param aTenantkey 钥匙
     * @return 钥匙
     */
    @Override
    public List<ATenantkey> selectATenantkeyList2(ATenantkey aTenantkey)
    {
        return aTenantkeyMapper.selectATenantkeyList2(aTenantkey);
    }
    @Override
    public List<ATenantkey> selectATenantkeyList3(ATenantkey aTenantkey)
    {
        return aTenantkeyMapper.selectATenantkeyList3(aTenantkey);
    }

    /**
     * 根据租户ID和类型查询钥匙
     *
     * @param tenantId 租户ID
     * @param type 钥匙类型
     * @return 钥匙集合
     */
    @Override
    public List<ATenantkey> selectATenantkeyByTenantIdAndType(Long tenantId, String type) {
        ATenantkey query = new ATenantkey();
        query.setTenantId(tenantId);
        query.setType(type);
        query.setFlgDelete(1); // 未删除的
        return aTenantkeyMapper.selectATenantkeyList3(query);
    }



    /**
     * 查询钥匙到期状态统计
     *
     * @param aTenantkey 钥匙
     * @return 统计结果
     */
    @Override
    @DataScope(deptAlias = "d")
    public JSONObject selectKeyExpiryStatusCount(ATenantkey aTenantkey) {
        // 设置未删除标记
        aTenantkey.setFlgDelete(1);
        
        // 创建JSON对象存储结果
        JSONObject result = new JSONObject();
        
        // 查询已到期的钥匙数量
        aTenantkey.setExpiryStatus("expired");
        int expiredCount = aTenantkeyMapper.selectKeyExpiryStatusCount(aTenantkey);
        result.put("expiredCount", expiredCount);
        
        // 查询即将到期的钥匙数量（3天内）
        aTenantkey.setExpiryStatus("expiring");
        int expiringCount = aTenantkeyMapper.selectKeyExpiryStatusCount(aTenantkey);
        result.put("expiringCount", expiringCount);
        
        // 查询有效期内的钥匙数量
        aTenantkey.setExpiryStatus("valid");
        int validCount = aTenantkeyMapper.selectKeyExpiryStatusCount(aTenantkey);
        result.put("validCount", validCount);
        
        return result;
    }

    /**
     * 新增钥匙
     * 
     * @param aTenantkey 钥匙
     * @return 结果
     */
    @Override
    public int insertATenantkey(ATenantkey aTenantkey)
    {

        return aTenantkeyMapper.insertATenantkey(aTenantkey);
    }

    /**
     * 修改钥匙
     * 
     * @param aTenantkey 钥匙
     * @return 结果
     */
    @Override
    public int updateATenantkey(ATenantkey aTenantkey)
    {
        aTenantkey.setUpdateTime(DateUtils.getNowDate());



        return aTenantkeyMapper.updateATenantkey(aTenantkey);
    }

    @Override
    public int updateATenantkeyHomeId(ATenantkey aTenantkey) {
        aTenantkey.setUpdateTime(DateUtils.getNowDate());
        return aTenantkeyMapper.updateATenantkeyHomeId(aTenantkey);
    }

    @Override
    public int updateATenantkeyMac(ATenantkey aTenantkey) {
        aTenantkey.setUpdateTime(DateUtils.getNowDate());
        return aTenantkeyMapper.updateATenantkeyMac(aTenantkey);
    }

    /**
     * 批量删除钥匙
     * 
     * @param ids 需要删除的钥匙主键
     * @return 结果
     */
//    @Override
//    public int deleteATenantkeyByIds(Long[] ids)
//    {
//        return aTenantkeyMapper.deleteATenantkeyByIds(ids);
//    }
//    /**
//     * 批量删除钥匙
//     *
//     * @param ids 需要删除的钥匙主键
//     * @return 结果
//     */
//    @Override
//    public int deleteATenantkeyByIds2(Long[] ids)
//    {
//        return aTenantkeyMapper.deleteATenantkeyByIds2(ids);
//    }

    /**
     * 删除钥匙信息
     * 
     * @param id 钥匙主键
     * @return 结果
     */
    @Override
    public int deleteATenantkeyById(Long id)
    {
        return aTenantkeyMapper.deleteATenantkeyById(id);
    }



    @Override
    public int deleteATenantkeyAndCreateTask(ATenantkey aTenantkey) {
//        taskMapper.deleteATaskByTarId(aTenantkey.getId());
        // 只处理密码类型的钥匙
        if ("1".equals(aTenantkey.getType()) && aTenantkey.getPwdId() != null)  {

            if(aTenantkey.getStatus()==0) {
                aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});
            }
            // 远程删除密码钥匙
            JSONObject resp = lockApiService.apartmentDelKey(aTenantkey.getPwdId());
            int resultCode = resp.getIntValue("resultCode");
            if (resultCode == 500002) {
                // 钥匙不存在，直接物理删除
                return aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});

            } else if (resultCode == 0) { // 删除成功，标记为删除
                return aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});
            } else if (resultCode == 500001 || resultCode == 500003 || resultCode == 500004) {
                ATenantkey aTenantkey1 = new ATenantkey();
                aTenantkey1.setId(aTenantkey.getId());
                aTenantkey1.setFlgDelete(0); // 0为逻辑删除
                aTenantkey1.setStatus(0);
                aTenantkeyMapper.updateATenantkey(aTenantkey1);
                throw new RuntimeException("远程删除钥匙失败: " + resp.getString("reason"));
            } else {
                ATenantkey aTenantkey1 = new ATenantkey();
                aTenantkey1.setId(aTenantkey.getId());
                aTenantkey1.setFlgDelete(0); // 0为逻辑删除
                aTenantkey1.setStatus(0);
                aTenantkeyMapper.updateATenantkey(aTenantkey1);
                // 其他未知情况也抛异常
                throw new RuntimeException("远程删除钥匙失败: " + resp.toJSONString());
            }

        }
        // 处理卡片类型的钥匙
        else if ("2".equals(aTenantkey.getType()) && aTenantkey.getPwdId() != null) {

            if(aTenantkey.getStatus()==0) {
                 aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});
            }
                // 远程删除卡片钥匙
                JSONObject resp = lockApiService.apartmentDelKey(aTenantkey.getPwdId());
                int resultCode = resp.getIntValue("resultCode");
                if (resultCode == 500002) {
                    // 钥匙不存在，直接物理删除
                    return aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});

                } else if (resultCode == 0) { // 删除成功，标记为删除
                    return aTenantkeyMapper.deleteATenantkeyByIdsRel(new Long[]{aTenantkey.getId()});
                } else if (resultCode == 500001 || resultCode == 500003 || resultCode == 500004) {
                    ATenantkey aTenantkey1 = new ATenantkey();
                    aTenantkey1.setId(aTenantkey.getId());
                    aTenantkey1.setFlgDelete(0); // 0为逻辑删除
                    aTenantkey1.setStatus(0);
                    aTenantkeyMapper.updateATenantkey(aTenantkey1);
                    throw new RuntimeException("远程删除钥匙失败: " + resp.getString("reason"));
                } else {
                    ATenantkey aTenantkey1 = new ATenantkey();
                    aTenantkey1.setId(aTenantkey.getId());
                    aTenantkey1.setFlgDelete(0); // 0为逻辑删除
                    aTenantkey1.setStatus(0);
                    aTenantkeyMapper.updateATenantkey(aTenantkey1);
                    // 其他未知情况也抛异常
                    throw new RuntimeException("远程删除钥匙失败: " + resp.toJSONString());
                }

        }else{
            return 1;
        }

    }

    /**
     * 简单查询卡片在房间中是否存在（不包含复杂关联）
     *
     * @param aTenantkey 查询条件
     * @return 钥匙集合
     */
    @Override
    public List<ATenantkey> selectATenantkeySimple(ATenantkey aTenantkey) {
        return aTenantkeyMapper.selectATenantkeySimple(aTenantkey);
    }

}
